package aiku.numericalcontroloa.Service.Impl;

import aiku.numericalcontroloa.Base.Utils.BaseEnum;
import aiku.numericalcontroloa.Base.Utils.HttpStatus;
import aiku.numericalcontroloa.Base.Utils.Result;
import aiku.numericalcontroloa.Mapper.CompanyCulture.LearnRecordMapper;
import aiku.numericalcontroloa.Mapper.CompanyCulture.MaterialMapper;
import aiku.numericalcontroloa.Mapper.DepartmentManagement.EmployeeDepartmentMapper;
import aiku.numericalcontroloa.Mapper.ExamineMapper;
import aiku.numericalcontroloa.Mapper.OrderManagement.OrderCommissionMapper;
import aiku.numericalcontroloa.Mapper.RoleMapper;
import aiku.numericalcontroloa.Mapper.SysUserRoleMapper;
import aiku.numericalcontroloa.Mapper.UserMapper;
import aiku.numericalcontroloa.Model.Dto.PageSelect;
import aiku.numericalcontroloa.Model.Dto.SysUserDto;
import aiku.numericalcontroloa.Model.Dto.UserDto;
import aiku.numericalcontroloa.Model.Dto.WxLoginDto;
import aiku.numericalcontroloa.Model.Entity.CompanyCulture.LearnRecord;
import aiku.numericalcontroloa.Model.Entity.CompanyCulture.Material;
import aiku.numericalcontroloa.Model.Entity.DepartmentManagement.EmployeeDepartment;
import aiku.numericalcontroloa.Model.Entity.Examine;
import aiku.numericalcontroloa.Model.Entity.OrderManagement.OrderCommission;
import aiku.numericalcontroloa.Model.Entity.Role;
import aiku.numericalcontroloa.Model.Entity.SysUserRole;
import aiku.numericalcontroloa.Model.Entity.User;
import aiku.numericalcontroloa.Model.Vo.UserVo;
import aiku.numericalcontroloa.Model.Vo.SalesmanVo;
import aiku.numericalcontroloa.Service.UserService;
import aiku.numericalcontroloa.enums.RoleEnum;
import aiku.numericalcontroloa.project.system.mapper.SysRoleMapper;
import aiku.numericalcontroloa.project.system.pojo.entity.SysRole;
import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.json.JSONException;
import org.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Author 黄广庭
 * @Date 2024/1/6 17:30
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{

    private final UserMapper userMapper;
    private final RoleMapper roleMapper;
    private final SysRoleMapper sysRoleMapper;
    private final MaterialMapper materialMapper;
    private final LearnRecordMapper learnRecordMapper;
    private final EmployeeDepartmentMapper employeeDepartmentMapper;
    private final OrderCommissionMapper orderCommissionMapper;

    @Autowired
    private ExamineMapper examineMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    public UserServiceImpl(UserMapper userMapper, RoleMapper roleMapper, SysRoleMapper sysRoleMapper, MaterialMapper materialMapper, LearnRecordMapper learnRecordMapper, EmployeeDepartmentMapper employeeDepartmentMapper, OrderCommissionMapper orderCommissionMapper) {
        this.userMapper = userMapper;
        this.roleMapper = roleMapper;
        this.sysRoleMapper = sysRoleMapper;
        this.materialMapper = materialMapper;
        this.learnRecordMapper = learnRecordMapper;
        this.employeeDepartmentMapper = employeeDepartmentMapper;
        this.orderCommissionMapper = orderCommissionMapper;
    }

    @Override
    public Result login(UserDto userDto) {
        if (userDto == null || userDto.getEmpno() == null)
            return new Result(HttpStatus.BAD_REQUEST,"缺少参数");
        if (userDto.getEmpno().isEmpty() && userDto.getPassword().isEmpty())
            return new Result(HttpStatus.BAD_REQUEST,"缺少参数");
        LambdaQueryWrapper<User> userLQW = new LambdaQueryWrapper<>();
        // 用姓名登录，且在职
        userLQW.eq(User::getState,BaseEnum.USER_INCUMBENCY.getCodeInt()).eq(User::getNickName,userDto.getEmpno());
        User logUser = userMapper.selectOne(userLQW);
        if (logUser == null){
            // 如果等于空，则用手机号登录
            userLQW = new LambdaQueryWrapper<>();
            userLQW.eq(User::getState,BaseEnum.USER_INCUMBENCY.getCodeInt()).eq(User::getPhone,userDto.getEmpno());
            logUser = userMapper.selectOne(userLQW);
        }
        // 还是为空，账号不存在
        if (logUser == null){
            return new Result(HttpStatus.BAD_REQUEST,"账号不存在");
        }
       // 不为空，对比密码
        String password = SaSecureUtil.aesDecrypt("b819e0ac", logUser.getPassword());
        if (password.equals(userDto.getPassword())){
            // 登录成功
            StpUtil.login(logUser.getId());
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(logUser,userVo);
            // 设置角色id
            SysRole sysRole = sysRoleMapper.selectById(logUser.getRoleId());
            if (sysRole == null){
                return new Result(HttpStatus.BAD_REQUEST,"参数错误");
            }
            // 角色名
            userVo.setRoleName(sysRole.getNameZh());
            Map<String, Object> result = new HashMap<>();
            result.put("OaAuth",StpUtil.getTokenValue());
            result.put("loginUser",userVo);
            return Result.success("登录成功",result);
        }
        return new Result(HttpStatus.BAD_REQUEST,"账号或密码错误");
    }

    @Override
    @Transactional
    public Result addUser(UserDto userDto) {
        if (userDto == null || (userDto.getNickName() == null || userDto.getNickName().isEmpty()))
            return new Result(HttpStatus.BAD_REQUEST,"缺少参数");
        LambdaUpdateWrapper<User> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        // 先查询是否有同名
        lambdaUpdateWrapper.eq(User::getNickName,userDto.getNickName());
        User user = userMapper.selectOne(lambdaUpdateWrapper);
        if (user != null)
            return new Result(HttpStatus.BAD_REQUEST,"员工已存在");
        // 没有同名则查询是否有相同电话号码
        lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(User::getPhone,userDto.getPhone());
        user = userMapper.selectOne(lambdaUpdateWrapper);
        if (user != null){
            return new Result(HttpStatus.BAD_REQUEST,"手机号已存在");
        }
        user = new User();
        // 员工id
        user.setId(UUID.randomUUID().toString());
        user.setOpenId(userDto.getOpenId());
        // user.setEmpno(userDto.getEmpno());
        user.setNickName(userDto.getNickName());
        // 密码加密
        String salt = "b819e0ac";
        String ciphertext = SaSecureUtil.aesEncrypt(salt, userDto.getPassword());
        user.setPassword(ciphertext);
        // 设置性别
        user.setSex(userDto.getSex());
        // 默认角色：员工
        user.setRoleId(RoleEnum.ROLE_8.getCodeToString());
        user.setPhone(userDto.getPhone());
        userMapper.insert(user);

        // 查询所有学习资料和培训视频，给用户添加学习记录
        LambdaQueryWrapper<Material> materialWrapper = new LambdaQueryWrapper<>();
        materialWrapper.eq(Material::getDeleted,BaseEnum.DELETED_NO)
                .in(Material::getType,Arrays.asList(BaseEnum.MATERIAL_LEARN.getCodeInt(), BaseEnum.MATERIAL_TRAIN.getCodeInt()));
        List<Material> materialList = materialMapper.selectList(materialWrapper);
        if (materialList.size() > 0){
            User finalUser = user;
            materialList.forEach(material -> {
                LearnRecord learnRecord = new LearnRecord();
                learnRecord.setMaterialId(material.getId());
                learnRecord.setUserId(finalUser.getId());
                learnRecordMapper.insert(learnRecord);
            });
        }
        return Result.success("添加成功");
    }

    @Override
    @Transactional
    public Result updateUser(UserDto userDto) {
        if (userDto == null){
            return new Result(HttpStatus.BAD_REQUEST,"缺少参数");
        }
        User user = userMapper.selectById(userDto.getId());
        if (user == null){
            return new Result(HttpStatus.BAD_REQUEST,"参数错误");
        }
        User loginUser = userMapper.selectById(StpUtil.getLoginIdAsString());
        // 修改用户头像
        user.setImage(userDto.getImage());
        // 修改用户昵称
        user.setNickName(userDto.getNickName());
        // 修改用户性别
        user.setSex(userDto.getSex());
        // 修改用户手机号
        user.setPhone(userDto.getPhone());
        if (loginUser.getRoleId().equals(RoleEnum.ROLE_1.getCodeToString())){
            // 超级管理员可修改
            // 角色
            user.setRoleId(userDto.getRoleId());
            // 查询用户角色表
            LambdaQueryWrapper<SysUserRole> sysUserRoleLQW = new LambdaQueryWrapper<>();
            sysUserRoleLQW.eq(SysUserRole::getUserId,user.getId());
            SysUserRole sysUserRole = sysUserRoleMapper.selectOne(sysUserRoleLQW);
            if (sysUserRole == null){
                // 创建
                sysUserRole = new SysUserRole();
                sysUserRole.setUserId(user.getId());
                sysUserRole.setRoleId(Integer.valueOf(user.getRoleId()));
                sysUserRoleMapper.insert(sysUserRole);
            }else {
                // 修改用户角色表
                sysUserRole.setRoleId(Integer.valueOf(user.getRoleId()));
                LambdaUpdateWrapper<SysUserRole> sysUserRoleLUW = new LambdaUpdateWrapper<>();
                sysUserRoleLUW.eq(SysUserRole::getId,sysUserRole.getId())
                        .set(SysUserRole::getRoleId,sysUserRole.getRoleId());
                sysUserRoleMapper.update(null,sysUserRoleLUW);
            }
            // 修改用户状态
            user.setState(user.getState());
            // 修改用户提成点
            // 先查询用户提成记录
            LambdaQueryWrapper<OrderCommission> orderCommissionLQW = new LambdaQueryWrapper<>();
            orderCommissionLQW.eq(OrderCommission::getUserId,user.getId());
            OrderCommission orderCommission = orderCommissionMapper.selectOne(orderCommissionLQW);
            if (orderCommission != null){
                // 不为空，删除该提成记录
                orderCommissionMapper.deleteById(orderCommission.getId());
            }
            // 创建新的记录
            orderCommission = new OrderCommission();
            orderCommission.setUserId(user.getId());
            orderCommission.setCommission(userDto.getPercentage());
            orderCommissionMapper.insert(orderCommission);
        }
        LambdaUpdateWrapper<User> userWrapper = new LambdaUpdateWrapper<>();
        userWrapper.eq(User::getId,user.getId()).eq(User::getDeleted,0)
                .set(User::getNickName,user.getNickName())
                .set(User::getRoleId,user.getRoleId())
                .set(User::getSex,user.getSex())
                .set(User::getImage,user.getImage())
                .set(User::getPhone,user.getPhone())
                .set(User::getState,user.getState());
        userMapper.update(null,userWrapper);
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user,userVo);
        return Result.success("修改成功",userVo);
    }

    @Override
    @Transactional
    public Result deleteUser(UserDto userDto) {
        if (userDto == null)
            return new Result(HttpStatus.BAD_REQUEST,"参数为空");
        User user = userMapper.selectById(userDto.getId());
        if (user == null)
            return new Result(HttpStatus.BAD_REQUEST,"参数错误");
        userMapper.deleteById(user.getId());
        // 删除用户学习记录
        LambdaQueryWrapper<LearnRecord> learnRecordLQW = new LambdaQueryWrapper<>();
        learnRecordLQW.eq(LearnRecord::getUserId,user.getId());
        learnRecordMapper.delete(learnRecordLQW);
        return Result.success("删除成功");
    }

    @Override
    public Result getUserList(PageSelect pageSelect) {
        if (pageSelect == null)
            return new Result(HttpStatus.BAD_REQUEST,"参数为空");
        Page<User> page = new Page<>(pageSelect.getCurrentPage(),pageSelect.getPageSize());
        LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(User::getDeleted,0).eq(User::getState,1);
        Page<User> userListPage = userMapper.selectPage(page, userWrapper);
        List<UserVo> userList = new ArrayList<>();
        userListPage.getRecords().forEach(user -> {
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(user,userVo);
            // 设置角色类型
            Role role = roleMapper.selectById(user.getRoleId());
            userVo.setRoleType(role.getRoleType());
            // 设置提成点
            LambdaQueryWrapper<OrderCommission> orderCommissionLQW = new LambdaQueryWrapper<>();
            orderCommissionLQW.eq(OrderCommission::getUserId,user.getId());
            OrderCommission orderCommission = orderCommissionMapper.selectOne(orderCommissionLQW);
            if (orderCommission != null){
                userVo.setPercentage(orderCommission.getCommission());
            }
            userList.add(userVo);
        });
        return Result.success("查询成功",userList);
    }

    @Override
    public Result getUser(String id) {
        LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(User::getId,id).eq(User::getDeleted,0);
        User user = userMapper.selectOne(userWrapper);
        if (user == null){
            return new Result(HttpStatus.BAD_REQUEST,"没有该用户");
        }
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user,userVo);
        // 设置提成点
        LambdaQueryWrapper<OrderCommission> orderCommissionLQW = new LambdaQueryWrapper<>();
        orderCommissionLQW.eq(OrderCommission::getUserId,user.getId());
        OrderCommission orderCommission = orderCommissionMapper.selectOne(orderCommissionLQW);
        if (orderCommission != null){
            userVo.setPercentage(orderCommission.getCommission());
        }
        return Result.success("查询成功",userVo);
    }

    @Override
    public Result verifyPassword(UserDto userDto) {
        User user = userMapper.selectById(StpUtil.getLoginId().toString());
        // 密码验证
        String password = SaSecureUtil.aesDecrypt("b819e0ac", user.getPassword());
        if (password.equals(userDto.getPassword()))
            return Result.success("密码验证成功");
        return new Result(HttpStatus.BAD_REQUEST,"密码验证失败");
    }

    @Override
    public Result changePassword(UserDto userDto) {
        if (userDto == null || userDto.getId() == null)
            return new Result(HttpStatus.BAD_REQUEST,"缺少参数");
        User user = userMapper.selectById(userDto.getId());
        if (user == null){
            return new Result(HttpStatus.BAD_REQUEST,"参数错误");
        }
        // 密码加密
        String salt = "b819e0ac";
        String ciphertext = SaSecureUtil.aesEncrypt(salt, userDto.getPassword());
        user.setPassword(ciphertext);
        LambdaUpdateWrapper<User> userWrapper = new LambdaUpdateWrapper<>();
        userWrapper.eq(User::getId,user.getId())
                .set(User::getPassword,user.getPassword());
        userMapper.update(null, userWrapper);
        return Result.success("修改成功");
    }

    @Override
    public Result resetPassword(UserDto userDto) {
        if (userDto == null){
            return new Result(HttpStatus.BAD_REQUEST,"缺少参数");
        }
        if (userDto.getId() == null){
            return new Result(HttpStatus.BAD_REQUEST,"缺少参数");
        }
        // 查询该账号
        User user = userMapper.selectById(userDto.getId());
        if (user == null){
            return new Result(HttpStatus.BAD_REQUEST,"该账号不存在");
        }
        // 使用该账号手机号后四位作为密码
        String lastFourDigits = user.getPhone().substring(user.getPhone().length()-4);
        System.out.println("lastFourDigits=====>"+lastFourDigits);
        // 密码加密
        String salt = "b819e0ac";
        String ciphertext = SaSecureUtil.aesEncrypt(salt, lastFourDigits);
        LambdaUpdateWrapper<User> userLUW = new LambdaUpdateWrapper<>();
        userLUW.eq(User::getId,userDto.getId()).set(User::getPassword,ciphertext);
        userMapper.update(null,userLUW);
        return Result.success("重置成功");
    }

    @Override
    public Result wxLogin(WxLoginDto wxLoginDto) throws IOException, JSONException {
        if (wxLoginDto == null || wxLoginDto.getCode() == null){
            return new Result(HttpStatus.BAD_REQUEST,"缺少参数");
        }
        String openId = getOpenId(wxLoginDto.getCode());
        // 判断是否有该用户
        LambdaQueryWrapper<User> userLQW = new LambdaQueryWrapper<>();
        // 根据openId查询，且状态为在职
        userLQW.eq(User::getState,BaseEnum.USER_INCUMBENCY.getCodeInt()).eq(User::getOpenId,openId);
        User loginUser = userMapper.selectOne(userLQW);
        if (loginUser == null){
            // 用户为空，登录失败
            return new Result(HttpStatus.NO_CONTENT,"自动登录失败");
        }
        // 用户不为空，登录成功
        // 做登录处理
        StpUtil.login(loginUser.getId());
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(loginUser,userVo);
        // 设置角色id
        SysRole sysRole = sysRoleMapper.selectById(loginUser.getRoleId());
        if (sysRole == null){
            return new Result(HttpStatus.BAD_REQUEST,"参数错误");
        }
        // 角色名
        userVo.setRoleName(sysRole.getNameZh());
        Map<String,Object> result = new HashMap<>();
        result.put("OaAuth",StpUtil.getTokenValue());
        result.put("loginUser",userVo);
        return Result.success("登录成功",result);
    }

    @Override
    public Result bindWx(WxLoginDto wxLoginDto) throws IOException, JSONException {
        if (wxLoginDto == null || wxLoginDto.getCode() == null){
            return new Result(HttpStatus.BAD_REQUEST,"缺少参数");
        }
        String openId = getOpenId(wxLoginDto.getCode());
        LambdaQueryWrapper<User> userLQW = new LambdaQueryWrapper<>();
        userLQW.eq(User::getState,BaseEnum.USER_INCUMBENCY.getCodeInt()).eq(User::getOpenId,openId);
        User user = userMapper.selectOne(userLQW);
        if (wxLoginDto.getIsBind() == 0){
            // 绑定
            if (user != null){
                // 已绑定账号，判断是否绑定的登录账号
                if (!user.getId().equals(StpUtil.getLoginIdAsString())){
                    // 绑定账号与登录账号不一致
                    return new Result(HttpStatus.NO_CONTENT,"该微信已绑定其他账号");
                }else {
                    return Result.success("已绑定");
                }
            }else {
                // 未绑定，与当前登录账号绑定
                LambdaUpdateWrapper<User> userLUW = new LambdaUpdateWrapper<>();
                userLUW.eq(User::getId,StpUtil.getLoginIdAsString()).set(User::getOpenId,openId);
                userMapper.update(null,userLUW);
                return Result.success("绑定成功");
            }
        }else {
            // 解绑
            if (user != null){
                // 已绑定账号，解绑
                LambdaUpdateWrapper<User> userLUW = new LambdaUpdateWrapper<>();
                userLUW.eq(User::getId,user.getId()).set(User::getOpenId,null);
                userMapper.update(null,userLUW);
                return Result.success("解绑成功");
            }else {
                // 未绑定账号
                return Result.success("已解绑");
            }
        }
    }

    @Value("${numericalControlOa.appId}")
    private String appId;

    @Value("${numericalControlOa.appSecret}")
    private String appSecret;

    @Value("${numericalControlOa.wxApiUrl}")
    private String wxApiUrl;

    protected String getOpenId(String code) throws IOException, JSONException{
        // 拼接
        String url = wxApiUrl;//微信登录接口url
        url += "?appid=" + appId;//小程序id
        url += "&secret=" + appSecret;//小程序密钥
        url += "&js_code=" + code;
        url += "&grant_type=authorization_code";
        url += "&connect_redirect=1";

        String res = "";
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        CloseableHttpResponse response = null;
        // 创建httpGet请求
        HttpGet httpget = new HttpGet(url);
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(5000)
                .setConnectionRequestTimeout(5000)
                .setSocketTimeout(5000)
                .setRedirectsEnabled(false).build();
        httpget.setConfig(requestConfig);
        // 执行请求
        response = httpClient.execute(httpget);
        // 得到返回数据
        HttpEntity responseEntity = response.getEntity();
        //System.out.println("响应状态为:" + response.getStatusLine());
        String openId = "";
        if (responseEntity != null) {
            res = EntityUtils.toString(responseEntity);
//            System.out.println("响应内容长度为=====>" + responseEntity.getContentLength());
//            System.out.println("响应内容为=====>" + res);
            JSONObject jsonObject = new JSONObject(res);
            // 将JSONObject转换为Map
            Map<String, String> map = new HashMap<>();
            map.put("openid", jsonObject.getString("openid"));
            openId = map.get("openid");
        }
        // 释放资源
        httpClient.close();
        response.close();
        return openId;
    }

    /**
     * 通过id查询该用户是否为管理员
     * @param id
     * @return
     */
    @Override
    public User isAdmin(String id) {
        SysRole sysRole = sysRoleMapper.selectOne(new LambdaQueryWrapper<SysRole>().eq(SysRole::getNameZh, "超级管理员"));
        //查询用户是否为管理员
        User user = userMapper.selectById(id);
        if (user.getRoleId().equals(String.valueOf(sysRole.getId()))) {
            return user;
        }
        return null;
    }

    /**
     * 通过用户id查询角色信息
     * @param id
     * @return
     */
    public SysRole isAdminInfo(String id) {
        User user = userMapper.selectById(id);
        SysRole sysRole = sysRoleMapper.selectOne(new LambdaQueryWrapper<SysRole>().eq(SysRole::getId,user.getRoleId()));
        return sysRole;
    }

    /**
     * 管理员添加用户
     * @param sysUserDto
     * @return
     */
    @Override
    @Transactional
    public Result adminAddUser(SysUserDto sysUserDto) {
        //查询是否有权限
        //用户id
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getId,StpUtil.getLoginIdAsString());
        User userOne = userMapper.selectOne(queryWrapper);
        if (userOne == null) {
            return Result.error("用户不存在");
        }
        //查询用户是否为管理员
        if (!userOne.getRoleId().equals("1")) {
            return new Result(HttpStatus.FORBIDDEN,"没有权限访问！");
        }
        //查询用户是否存在
        LambdaUpdateWrapper<User> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        // 先查询是否有同名
        lambdaUpdateWrapper.eq(User::getNickName,sysUserDto.getNickName());
        User user = userMapper.selectOne(lambdaUpdateWrapper);
        if (user != null)
            return new Result(HttpStatus.BAD_REQUEST,"用户已存在");
        // 没有同名则查询是否有相同电话号码
        lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(User::getPhone,sysUserDto.getPhone());
        user = userMapper.selectOne(lambdaUpdateWrapper);
        if (user != null){
            return new Result(HttpStatus.BAD_REQUEST,"手机号已存在");
        }
        user = new User();
//        user.setEmpno(sysUserDto.getEmpno());
        // 姓名
        user.setNickName(sysUserDto.getNickName());
        // 手机号
        user.setPhone(sysUserDto.getPhone());
        // 性别
        user.setSex(sysUserDto.getSex());
        // 头像
        user.setImage("user.png");
        //密码加密
        String salt = "b819e0ac";
        String ciphertext = SaSecureUtil.aesEncrypt(salt, sysUserDto.getPassword());
        user.setPassword(ciphertext);
        // 状态
        user.setState(sysUserDto.getState());
        // 角色
        user.setRoleId(sysUserDto.getRoleId());
        userMapper.insert(user);

        // 提成点
        if (user.getRoleId().equals(RoleEnum.ROLE_3.getCodeToString()) ||
                user.getRoleId().equals(RoleEnum.ROLE_7.getCodeToString())){
            // 只有业务员和售后员
            // 添加提成记录
            OrderCommission orderCommission = new OrderCommission();
            orderCommission.setUserId(user.getId());
            orderCommission.setCommission(sysUserDto.getPercentage());
            orderCommissionMapper.insert(orderCommission);
        }

        //添加关系关联表
        Examine examine = new Examine();
        examine.setUserId(user.getId());
        examineMapper.insert(examine);

        //添加路由角色表
        SysUserRole userRole = new SysUserRole();
        userRole.setUserId(user.getId());
        userRole.setRoleId(Integer.valueOf(user.getRoleId()));
        sysUserRoleMapper.insert(userRole);

        // 查询所有学习资料和培训视频，给用户添加学习记录
        LambdaQueryWrapper<Material> materialWrapper = new LambdaQueryWrapper<>();
        materialWrapper.eq(Material::getDeleted,BaseEnum.DELETED_NO)
                .in(Material::getType,Arrays.asList(BaseEnum.MATERIAL_LEARN.getCodeInt(), BaseEnum.MATERIAL_TRAIN.getCodeInt()));
        List<Material> materialList = materialMapper.selectList(materialWrapper);
        if (materialList.size() > 0){
            User finalUser = user;
            materialList.forEach(material -> {
                LearnRecord learnRecord = new LearnRecord();
                learnRecord.setMaterialId(material.getId());
                learnRecord.setUserId(finalUser.getId());
                learnRecordMapper.insert(learnRecord);
            });
        }
        return Result.success("添加成功");
    }

    /**
     * 管理员查询所有用户
     * @param
     * @return
     */
    @Override
    public Result adminGetUser() {
        //查询是否有权限
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getId,StpUtil.getLoginIdAsString());
        User userOne = userMapper.selectOne(queryWrapper);
        if (userOne == null) {
            return Result.error("用户不存在");
        }
        //查询用户是否为管理员
        if (!userOne.getRoleId().equals("1")) {
            return Result.success("没有权限");
        }
        List<User> users = userMapper.selectList(null);
        return Result.success(users);
    }

    /**
     * 管理员查询所有业务员
     * @return
     */
    @Override
    public Result adminGetSalesman() {
        //查询所有业务员
        SysRole roles = sysRoleMapper.selectOne(new LambdaQueryWrapper<SysRole>().eq(SysRole::getNameZh, "业务员"));
        List<User> users = userMapper.selectList(new LambdaQueryWrapper<User>().eq(User::getRoleId, roles.getId()));
        //封装成salesmanVo
        List<SalesmanVo> salesmanVos = new ArrayList<>();
        for (User user : users) {
            SalesmanVo salesmanVo = new SalesmanVo();
            BeanUtils.copyProperties(user,salesmanVo);
            salesmanVos.add(salesmanVo);
        }
        return Result.success(salesmanVos);
    }

    @Override
    public Result fuzzyQuery(UserDto userDto) {
        if (userDto == null){
            return new Result(HttpStatus.BAD_REQUEST,"缺少参数(userDto is null)");
        }
        Page<User> userPage = new Page<>();
        if (userDto.getCurrentPage() == null && userDto.getPageSize() == null){
            userPage.setCurrent(1);
            userPage.setSize(1000);
        }else {
            userPage.setCurrent(userDto.getCurrentPage());
            userPage.setSize(userDto.getPageSize());
        }

        // 根据名字或者手机号进行模糊查询
        LambdaQueryWrapper<User> userLQW = new LambdaQueryWrapper<>();
        userLQW.orderByDesc(User::getCreateTime);
        // 根据角色权限查询
        if (userDto.getRoleId() != null && !userDto.getRoleId().isEmpty()){
            userLQW.eq(User::getRoleId,userDto.getRoleId());
        }
        if (userDto.getNickName() != null && !userDto.getNickName().isEmpty()){
            userLQW.eq(User::getState,BaseEnum.USER_INCUMBENCY.getCodeInt())
                    .and(lQW ->lQW.like(User::getNickName,userDto.getNickName())
                    .or()
                    .like(User::getPhone,userDto.getNickName()));
        }
        List<User> userList = userMapper.selectPage(userPage, userLQW).getRecords();
        List<UserVo> userVoList = new ArrayList<>();
        Map<String,Object> map = new HashMap<>();
        if (userList.isEmpty()){
            map.put("total",0);
            map.put("userVoList",userVoList);
            return Result.success("查询成功",map);
        }
        // 查角色
        Set<String> roleIdList = userList.stream().map(User::getRoleId).collect(Collectors.toSet());
        List<SysRole> sysRoleList = sysRoleMapper.selectBatchIds(roleIdList);
        // 根据角色id获取角色对象
        Map<Integer, SysRole> sysRoleMap = sysRoleList.stream().collect(Collectors.toMap(SysRole::getId, Function.identity()));


        // 查员工部门表
        List<String> userIdList = userList.stream().map(User::getId).collect(Collectors.toList());
        LambdaQueryWrapper<EmployeeDepartment> employeeDepartmentLQW = new LambdaQueryWrapper<>();
        employeeDepartmentLQW.in(EmployeeDepartment::getEmployeeId,userIdList);
        List<EmployeeDepartment> employeeDepartmentList = employeeDepartmentMapper.selectList(employeeDepartmentLQW);
        // 根据员工id获取部门id列表
        Map<String, List<String>> departmentIdListMap = new HashMap<>();
        for (EmployeeDepartment employeeDepartment : employeeDepartmentList){
            if (departmentIdListMap.containsKey(employeeDepartment.getEmployeeId())){
                departmentIdListMap.get(employeeDepartment.getEmployeeId()).add(employeeDepartment.getDepartmentId());
            }else {
                List<String> departmentIdList = new ArrayList<>();
                departmentIdList.add(employeeDepartment.getDepartmentId());
                departmentIdListMap.put(employeeDepartment.getEmployeeId(),departmentIdList);
            }
        }

        // 查提成点
        LambdaQueryWrapper<OrderCommission> orderCommissionLQW = new LambdaQueryWrapper<>();
        orderCommissionLQW.in(OrderCommission::getUserId,userIdList);
        List<OrderCommission> orderCommissionList = orderCommissionMapper.selectList(orderCommissionLQW);
        // 根据userId获取提成点对象
        Map<String, OrderCommission> commissionMap = orderCommissionList.stream().collect(Collectors.toMap(OrderCommission::getUserId, o -> orderCommissionList.stream()
                .filter(orderCommission -> orderCommission.getUserId().equals(o.getUserId()))
                .findFirst()
                .orElse(null)));

        for (User user : userList){
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(user,userVo);
            // 设置角色名
            SysRole sysRole = sysRoleMap.get(Integer.valueOf(user.getRoleId()));
            userVo.setRoleName(sysRole.getNameZh());
            // 设置所在部门
            if (departmentIdListMap.containsKey(user.getId())){
                List<String> departmentIdList = departmentIdListMap.get(user.getId());
                userVo.setDepartmentIdList(departmentIdList);
            }
            // 设置提成点
            if (commissionMap.containsKey(user.getId())){
                OrderCommission orderCommission = commissionMap.get(user.getId());
                userVo.setPercentage(orderCommission.getCommission());
            }
            userVoList.add(userVo);
        }
        map.put("total",userPage.getTotal());
        map.put("userVoList",userVoList);
        return Result.success("查询成功",map);
    }

    @Override
    public Result getUserWithDelete(String id) {
        User user = userMapper.selectByIdWithDelete(id);
        if (user == null){
            return new Result(HttpStatus.BAD_REQUEST,"没有该用户");
        }
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user,userVo);
        // 设置提成点
        LambdaQueryWrapper<OrderCommission> orderCommissionLQW = new LambdaQueryWrapper<>();
        orderCommissionLQW.eq(OrderCommission::getUserId,user.getId());
        OrderCommission orderCommission = orderCommissionMapper.selectOne(orderCommissionLQW);
        if (orderCommission != null){
            userVo.setPercentage(orderCommission.getCommission());
        }
        return Result.success("查询成功",userVo);
    }

//    @Override
//    @Transactional
//    public Result submitUser(UserDto userDto) {
//        if (userDto == null || userDto.getPhone() == null){
//            return new Result(HttpStatus.BAD_REQUEST,"参数为空");
//        }
//
//        LambdaQueryWrapper<User> userLQW = new LambdaQueryWrapper<>();
//        // 根据电话号码查询用户
//        userLQW.eq(User::getPhone,userDto.getPhone());
//        User user = userMapper.selectOne(userLQW);
//        // 根据openId查询用户
//        userLQW = new LambdaQueryWrapper<>();
//        userLQW.eq(User::getOpenId,userDto.getOpenId());
//        User oldUser = userMapper.selectOne(userLQW);
//        if (oldUser == null){
//            return new Result(HttpStatus.BAD_REQUEST,"参数错误");
//        }
//        UserVo userVo = new UserVo();
//        if (user == null){
//            // 电话号码查询user为空
//            // 更新oldUser
//            // 设置姓名
//            oldUser.setNickName(userDto.getNickName());
//            // 设置电话号码
//            oldUser.setPhone(userDto.getPhone());
//            // 更新数据
//            LambdaUpdateWrapper<User> userLUW = new LambdaUpdateWrapper<>();
//            userLUW.eq(User::getOpenId,oldUser.getOpenId())
//                    .set(User::getNickName,oldUser.getNickName())
//                    .set(User::getPhone,oldUser.getPhone());
//            userMapper.update(null,userLUW);
//            BeanUtils.copyProperties(oldUser,userVo);
//
//            //添加关系关联表
//            Examine examine = new Examine();
//            examine.setUserId(oldUser.getId());
//            examineMapper.insert(examine);
//
//            //添加路由角色表
//            SysUserRole userRole = new SysUserRole();
//            userRole.setUserId(oldUser.getId());
//            userRole.setRoleId(Integer.valueOf(oldUser.getRoleId()));
//            sysUserRoleMapper.insert(userRole);
//
//            // 查询所有学习资料和培训视频，给用户添加学习记录
//            LambdaQueryWrapper<Material> materialWrapper = new LambdaQueryWrapper<>();
//            materialWrapper.eq(Material::getDeleted,BaseEnum.DELETED_NO)
//                    .in(Material::getType,Arrays.asList(BaseEnum.MATERIAL_LEARN.getCodeInt(), BaseEnum.MATERIAL_TRAIN.getCodeInt()));
//            List<Material> materialList = materialMapper.selectList(materialWrapper);
//            if (materialList.size() > 0){
//                materialList.forEach(material -> {
//                    LearnRecord learnRecord = new LearnRecord();
//                    // 设置资料id
//                    learnRecord.setMaterialId(material.getId());
//                    // 设置用户id
//                    learnRecord.setUserId(oldUser.getId());
//                    learnRecordMapper.insert(learnRecord);
//                });
//            }
//        }else {
//            // user不为空，且oldUser不为空
//            // 判断user是否有openid
//            if (user.getOpenId() != null && !user.getOpenId().isEmpty()){
//                return new Result(HttpStatus.BAD_REQUEST,"该手机号已绑定其他微信号");
//            }
//            // 判断姓名是否重复
//            userLQW = new LambdaQueryWrapper<>();
//            userLQW.eq(User::getNickName,userDto.getNickName());
//            User user1 =  userMapper.selectOne(userLQW);
//            if (user1 != null && !user1.getPhone().equals(user.getPhone())){
//                return new Result(HttpStatus.BAD_REQUEST,"已有该姓名账号");
//            }
//            // 删除原来的openId账号
//            userMapper.physicsDeleteByOpenId(userDto.getOpenId());
//
//            // 设置openId
//            user.setOpenId(userDto.getOpenId());
//            // 更新数据
//            LambdaUpdateWrapper<User> userLUW = new LambdaUpdateWrapper<>();
//            userLUW.eq(User::getId,user.getId()).set(User::getOpenId,user.getOpenId());
//            userMapper.update(null,userLUW);
//            BeanUtils.copyProperties(user,userVo);
//
//        }
//        // 退出登录，销毁token
//        StpUtil.logout();
//        // 重新登录，分配token
//        StpUtil.login(userVo.getId());
//        Map<String,Object> map = new HashMap<>();
//        map.put("OaAuth",StpUtil.getTokenValue());
//        map.put("loginUser",userVo);
//        return Result.success("操作成功",map);
//    }


}
